#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

using namespace std;

enum
{
    SOCKET_ERR=1,
    BIND_ERR
};

class udpserver
{
public:
    udpserver(uint16_t port, const string& ip = "0.0.0.0"):_socketfd(-1), _ip(ip), _port(port)
    {}
    void init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd < 0)
        {
            cout << "socket fail, errno:" << errno << ", " << strerror(errno) << endl;
            exit(SOCKET_ERR);
        }
        cout << "socket over..." << endl;
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_ip.c_str());
        server.sin_port = htons(_port);
        if(bind(_socketfd, (struct sockaddr*)&server, sizeof(server)) < 0)
        {
            cout << "bind fail, errno:" << errno << ", " << strerror(errno) << endl;
            exit(BIND_ERR);
        }
        cout << "bind over..." << endl;
    }
    void run()
    {   
        char buffer[4096];
        while(true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                cout << "recv fail" << endl;
                continue;
            }
            buffer[n] = 0;
            string message = inet_ntoa(client.sin_addr);
            message += ":";
            message += to_string(ntohs(client.sin_port));
            message += "# ";
            message += buffer;
            if(sendto(_socketfd, message.c_str(), message.size(), 0, (struct sockaddr*)&client, len) < 0)
            {
                cout << "send fail, errno:" << errno << ", " << strerror(errno) << endl;
                continue;
            }
            cout << message << endl;
        }
    }
    ~udpserver()
    {}
private:
    int _socketfd;
    string _ip;
    unsigned short _port;
};